package com.benshou.bsoa.service.yida;

import com.aliyun.dingtalkyida_1_0.Client;
import com.aliyun.dingtalkyida_1_0.models.GetFormComponentDefinitionListHeaders;
import com.aliyun.dingtalkyida_1_0.models.GetFormComponentDefinitionListRequest;

import com.aliyun.dingtalkyida_1_0.models.GetFormComponentDefinitionListResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.benshou.bsoa.dto.yida.req.YiDaReq;
import com.benshou.bsoa.utils.CreateAccessTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * 宜搭相关表单组件
 * 获取的是组件定义列表定义
 * @auth hyh
 *  2025/04/30
 */
@Service
public class GetComponentsDefineService {
    @Value("${yida_app_code}")
    private String APP_CODE;

    @Value("${yida_app_secret}")
    private String APP_SECRET;

    @Autowired
    private CreateAccessTokenUtil createAccessTokenUtil;

    /**
     * 获取组件定义列表
     * @param yiDaReq
     * @return 组件定义列表的响应信息
     * @throws Exception
     */
    public GetFormComponentDefinitionListResponse getFormComponentDefinitionListRequest(YiDaReq yiDaReq) throws Exception {
        // 创建 Client
        Config config = new Config();
        config.protocol = "https";
        config.regionId = "central";
        Client client = new Client(config);
        // 准备 Headers
        GetFormComponentDefinitionListHeaders headers = new GetFormComponentDefinitionListHeaders();
        headers.xAcsDingtalkAccessToken = createAccessTokenUtil.getToken();

        // 准备 Request
        GetFormComponentDefinitionListRequest request = new GetFormComponentDefinitionListRequest()
                .setSystemToken(APP_SECRET)  // 宜搭类型中的应用密钥
                .setUserId(yiDaReq.getUserId())
                .setLanguage("zh_CN");
        try {

            GetFormComponentDefinitionListResponse formComponentDefinitionListWithOptions =
                    client.getFormComponentDefinitionListWithOptions(APP_CODE, yiDaReq.getFormUuid(), request, headers, new RuntimeOptions());
            return formComponentDefinitionListWithOptions;
        } catch (TeaException err) {
            throw new RuntimeException("Error occurred while saving form data: " + err.getMessage(), err);
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            throw new RuntimeException("Error occurred while saving form data: " + err.getMessage(), err);
        }
    }
}
